package com.dtcnet.skmvp.network.simpleNet;

import androidx.annotation.NonNull;

import java.util.List;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * @author snoopy
 */
public class ObserverUtil {
    public static <T> Observer<T> getObservable(List<Disposable> bind, SkObservable<T> skObservable) {
        return new Observer<T>() {
            private Disposable d;
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                this.d = d;
                skObservable.start(d);

                if (bind != null) {
                    try {
                        bind.add(d);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new RuntimeException("请检查List是否可执行.add方法");
                    }
                }
            }

            @Override
            public void onNext(@NonNull T t) {
                skObservable.onSuccess(t);
                d.dispose();
                if (bind != null) {
                    bind.remove(d);
                }
                skObservable.finish();
            }

            @Override
            public void onError(@NonNull Throwable t) {
                skObservable.onError(t);
                d.dispose();
                if (bind != null) {
                    bind.remove(d);
                }
                skObservable.finish();
            }

            @Override
            public void onComplete() {

            }
        };
    }
}
